<?php
namespace app\command;

use Symfony\Component\Console\Command\Command;
use Symfony\Component\Console\Input\InputInterface;
use Symfony\Component\Console\Input\InputOption;
use Symfony\Component\Console\Output\OutputInterface;
use think\facade\Db;

class DbRestore extends Command
{
    protected static $defaultName = 'db:restore';
    
    protected function configure()
    {
        $this->setDescription('Restore database from backup file')
             ->addOption('file', 'f', InputOption::VALUE_REQUIRED, 'Backup file to restore from');
    }
    
    protected function execute(InputInterface $input, OutputInterface $output)
    {
        $file = $input->getOption('file');
        if (!$file) {
            // 如果没有指定文件，使用最新的备份文件
            $backupFiles = glob(base_path() . '/database/backup_*.php');
            if (empty($backupFiles)) {
                $output->writeln('<error>No backup files found!</error>');
                return Command::FAILURE;
            }
            $file = end($backupFiles);
        }
        
        if (!file_exists($file)) {
            $output->writeln("<error>Backup file not found: $file</error>");
            return Command::FAILURE;
        }
        
        $backup = require $file;
        
        try {
            Db::startTrans();
            
            // 禁用外键检查
            Db::execute('SET FOREIGN_KEY_CHECKS = 0');
            
            foreach ($backup as $tableName => $tableData) {
                // 如果表存在则删除
                Db::execute("DROP TABLE IF EXISTS `$tableName`");
                
                // 创建表
                Db::execute($tableData['structure']);
                
                // 插入数据
                if (!empty($tableData['data'])) {
                    // 分批插入数据，避免数据量太大
                    foreach (array_chunk($tableData['data'], 1000) as $chunk) {
                        Db::table($tableName)->insertAll($chunk);
                    }
                }
            }
            
            // 启用外键检查
            Db::execute('SET FOREIGN_KEY_CHECKS = 1');
            
            Db::commit();
            $output->writeln('<info>Database restored successfully!</info>');
            return Command::SUCCESS;
            
        } catch (\Exception $e) {
            Db::rollback();
            $output->writeln('<error>Error during restore: ' . $e->getMessage() . '</error>');
            return Command::FAILURE;
        }
    }
} 